package top.zbsong.community.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import top.zbsong.community.dto.AccessTokenDTO;
import top.zbsong.community.dto.OAuthUser;
import top.zbsong.community.model.User;
import top.zbsong.community.provider.GiteeOAuthProvider;
import top.zbsong.community.provider.GithubOAtuhProvider;
import top.zbsong.community.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Create By songzb on 2021/4/23
 *
 * @author songzb
 */
@Controller
@Slf4j
public class AuthorizeController {
    @Autowired
    private GithubOAtuhProvider githubOAtuhProvider;
    @Autowired
    private GiteeOAuthProvider giteeOAuthProvider;

    @Autowired
    private UserService userService;


    @Value("${github.client.id}")
    private String githubClientId;
    @Value("${github.client.secret}")
    private String githubClientSecret;
    @Value("${github.redirect.uri}")
    private String githubRedirectUri;

    @Value("${gitee.client.id}")
    private String giteeClientId;
    @Value("${gitee.client.secret}")
    private String giteeClientSecret;
    @Value("${gitee.redirect.uri}")
    private String giteeRedirectUri;

    /**
     * Oauth的回调函数
     * @param code
     * @param state
     * @param response
     * @return
     */
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code, @RequestParam(name = "state") String state, HttpServletResponse response) {
        // 填入需要的参数给DTO
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(githubClientId);
        accessTokenDTO.setClient_secret(githubClientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(githubRedirectUri);
        // accessTokenDTO.setState(state);
        // 获取 accessToken
        String accessToken = githubOAtuhProvider.getAccessToken(accessTokenDTO);
        OAuthUser OAuthUser = null;
        if (accessToken != null) {
            // 1.接入Github认证登陆成功，获取到了用户信息
            OAuthUser = githubOAtuhProvider.getUser(accessToken);
            if (OAuthUser != null) {
                // 2.在本地登录，为该用户生成一个token
                // 把用户写入数据库
                User user = new User();
                String token = UUID.randomUUID().toString();
                user.setToken(token);
                user.setName(OAuthUser.getName());
                user.setAccountId(String.valueOf(OAuthUser.getId()));
                user.setAvatarUrl(OAuthUser.getAvatarUrl());
                userService.createOrUpdate(user);
                // 3.将token放入cookie
                response.addCookie(new Cookie("token", token));
                return "redirect:/";
            } else {
                log.error("callback get github error,{}", OAuthUser);
                // 登陆失败
                return "redirect:/";
            }
        } else {
            log.error("callback get github accessToken error,{}", accessToken);
            // 登陆失败
            return "redirect:/";
        }
    }


    @GetMapping("/gitee_callback")
    public String giteeCallback(@RequestParam(name = "code") String code, HttpServletResponse response) {
        // 填入需要的参数给DTO
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(giteeClientId);
        accessTokenDTO.setClient_secret(giteeClientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(giteeRedirectUri);


        // 获取 accessToken
        String accessToken = giteeOAuthProvider.getAccessToken(accessTokenDTO);
        OAuthUser OAuthUser = null;
        if (accessToken != null) {
            // 1.接入Github认证登陆成功，获取到了用户信息
            OAuthUser = giteeOAuthProvider.getUser(accessToken);
            if (OAuthUser != null) {
                // 2.在本地登录，为该用户生成一个token
                // 把用户写入数据库
                User user = new User();
                String token = UUID.randomUUID().toString();
                user.setToken(token);
                user.setName(OAuthUser.getName());
                user.setAccountId(String.valueOf(OAuthUser.getId()));
                user.setAvatarUrl(OAuthUser.getAvatarUrl());
                userService.createOrUpdate(user);
                // 3.将token放入cookie
                response.addCookie(new Cookie("token", token));
                return "redirect:/";
            } else {
                log.error("callback get gitee error,{}", OAuthUser);
                // 登陆失败
                return "redirect:/";
            }
        } else {
            log.error("callback get gitee accessToken error,{}", accessToken);
            // 登陆失败
            return "redirect:/";
        }
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
